package org.bbs.demo.utils.jwtutil;


import io.jsonwebtoken.*;
import org.bbs.demo.advice.TokenException;
import org.bbs.demo.utils.TokenUser;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTutil {

    public static String SIGN = "javabackend";
    public static final long EXPIRE_TIME = 3*30*60*1000;

    public static Claims parseToken(String token){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SIGN)
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        }catch (ExpiredJwtException e){
            throw new TokenException("token 已经过期");
        }catch (Exception e){
            throw new TokenException("token 解析异常");
        }
    }


    public static String createToken(TokenUser tokenuser){
        Map<String,Object> header = new HashMap<>();
        JwtBuilder jwtBuilder = Jwts.builder();

        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        header.put("type" , "JWT");
        header.put("algs" , "HS256");
        String jwtToken = jwtBuilder
                .setHeader(header)
                .claim("userid", tokenuser.getUserId())
                .claim("email", tokenuser.getMail())
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256,SIGN)
                .compact();
        return jwtToken;
    }

    public static String getUserID(String token){
        Claims claims = parseToken(token);
        String userid = claims.get("userid" , String.class);
        return userid;
    }

    public static String getMail(String token){
        Claims claims = parseToken(token);
        String email = claims.get("email" , String.class);
        return email;
    }

    public static boolean isExpiration(String token){
        Date expiration = parseToken(token).getExpiration();
        return expiration.before(new Date());
    }


}
